<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2019/2/27
 * Time: 17:35
 */

namespace app\api2\behavior;


use app\api2\Service\DemandService;
use think\Db;

class Cron
{
    function run(){
        //自动结束采购订单
        $this->end_purchase();
        //自动结束找人订单
        $this->end_recruit_worker();
        //自动结束询价订单
        $this->end_inquiry();
        //自动退回未入围的需求竞标
        $this->end_demand();
    }

    /**
     * 结束需求
     */
    private function end_demand(){
        $demand_ids=Db::name('member_demand')
            ->where('endtime','<',time())
            ->where('is_back_money',0)
            ->column('id');
        foreach ($demand_ids as $v){
            DemandService::back_money($v);
        }
    }

    /**
     * 结束询价订单
     */
    private function end_inquiry(){
        Db::transaction(function (){
            $ids=Db::name('inquiry')
                ->where('status',1)
                ->where('grab_sheet_end_time','<=',time()-2*24*60*60)
                ->column('id');
            Db::name('inquiry')
                ->where('status',1)
                ->where('grab_sheet_end_time','<=',time()-2*24*60*60)
                ->setField('status',2);
            $offer_list=Db::name('inquiry_offer')
                ->where('inquiry_id','in',$ids)
                ->where('status',1)
                ->field('mid,offer_money')
                ->select();
            foreach ($offer_list as $v){
                log_account_change($v['mid'],$v['offer_money'],0,'订单流标,团币返回账户',4);
            }
            Db::name('inquiry_offer')
                ->where('inquiry_id','in',$ids)
                ->setField('status',2);
        });
    }
    /**
     * 结束找人订单
     */
    private function end_recruit_worker(){
        Db::transaction(function (){
            $ids=Db::name('recruit_worker')
                ->where('status',1)
                ->where('grab_sheet_end_time','<=',time()-2*24*60*60)
                ->column('id');
            Db::name('recruit_worker')
                ->where('status',1)
                ->where('grab_sheet_end_time','<=',time()-2*24*60*60)
                ->setField('status',2);
            Db::name('recruit_worker_grab_sheet')
                ->where('recruit_worker_id','in',$ids)
                ->setField('status',-1);
        });
    }
    /**
     * 结束采购
     */
    private function end_purchase(){
        Db::name('purchase')
            ->where('status',1)
            ->where('grab_sheet_end_time','<=',time()-2*24*60*60)
            ->setField('status',2);
    }
}